import adminListView from '$v/adminList'

import {
    addAdminRequest,
    adminListRequest,
    deleteAdminRequest,
    isloginRequest
} from '$a/admin';

const showAdminList = async (res) => {
    //只要进入当前路由函数，则立马开始查询所有的管理员信息
    let adminListResult = null;
    try {
      adminListResult = await adminListRequest();
      console.log(adminListResult);
    } catch (e) {
      alert("获取管理员列表异常:" + e.message)
      //判断是否是权限异常
      if (!e.isLogin) {
        return router.go("/login");
    }
    }
    //渲染二级路由视图
    res.render(adminListView({
      adminList: adminListResult
    }));
  }
  
export default async (req, res) => {
    try {
        await isloginRequest()
    } catch (e) {
        alert(e.message)
        //判断是否是权限异常
        if (!e.isLogin) {
            return router.go("/login");
        }
    }
    await showAdminList(res)
    const oSaveAdmin = document.getElementById("saveAdminBtn");
    document.onclick = async function (e) {
        if (e.target.id === 'saveAdminBtn') {
            const adminNameValue = document.adminForm.adminName.value.trim();
            const passwordValue = document.adminForm.password.value.trim();
            const rePasswordValue = document.adminForm.rePassword.value.trim();
            if (!adminNameValue || !passwordValue || !rePasswordValue) {
                return alert("账号密码不能为空!!!!")
            }
            if (passwordValue !== rePasswordValue) {
                return alert("两次密码输入的不一致")
            }
            try {
                const re = await addAdminRequest({
                    adminName: adminNameValue,
                    password: passwordValue,
                    regTime: new Date().toLocaleString()
                })
                alert('添加成功')
                document.getElementById("closedd").click()
                document.adminForm.reset()
                showAdminList(res)
            } catch (e) {
                alert(e.message)
                //判断是否是权限异常
                if (!e.isLogin) {
                    document.getElementById("closedd").click()
                    return router.go("/login");
                }
            }

        }
        if (e.target.nodeName === "BUTTON" && e.target.parentNode.nodeName === "TD") {
            try {
                await deleteAdminRequest(e.target.dataset.adminname);
                alert("删除成功");
                //删除成功以后查询数据库重新渲染
                showAdminList(res)
            } catch (e) {
                alert(e.message)
                //判断是否是权限异常
                if (!e.isLogin) {
                    return router.go("/login");
                }
            }
        }
    }

}